package cn.devcat.sso.config.security;

import java.util.List;
import java.util.stream.Collectors;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson2.JSONObject;

import cn.devcat.sso.entity.DevcatRole;
import cn.devcat.sso.entity.DevcatUser;
import cn.devcat.sso.service.IDevcatRoleService;
import cn.devcat.sso.service.IDevcatUserService;
import lombok.extern.slf4j.Slf4j;

/**
 * 加载用户
 * @author huhailong
 *
 */
@Slf4j
@Service
public class DevcatUserDetailsService implements UserDetailsService {

	@Autowired
	IDevcatUserService userService;
	@Autowired
	IDevcatRoleService roleService;

	@Override
	public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
		log.info("load user name:{}",username);
		DevcatUser user = userService.getUserByUsername(username);
		log.info("user : {}",JSONObject.toJSONString(user));
		if(user == null) {
			throw new UsernameNotFoundException("用户名不存在");
		}
		List<DevcatRole> roleListByUserId = roleService.getRoleListByUserId(user.getId());
		String authorities = roleListByUserId.stream().map(DevcatRole::getRoleCode).collect(Collectors.joining(","));
		log.info("roles : {}",authorities);

		user.setAuthorities(AuthorityUtils.commaSeparatedStringToAuthorityList(authorities));
		return user;
	}

}
